<?php

if_get('/rule_relations', function ()
{/*{{{*/
    list(
        $inputs['source_tag_id'], $inputs['outcome_tag_id'], $inputs['engine_rule_id'], $inputs['engine_log_id']
    ) = input_list(
        'source_tag_id', 'outcome_tag_id', 'engine_rule_id', 'engine_log_id'
    );

    $inputs = array_filter($inputs, 'not_null');

    $rule_relations = dao('rule_relation')->find_all_by_column($inputs);

    return [
        'count' => count($rule_relations),
        'rule_relations' => array_build($rule_relations, function ($id, $rule_relation) {
            return [
                null,
                [
                    'id' => $rule_relation->id,
                    'source_tag_display' => $rule_relation->source_tag->display_for_outcome_rule_relations_source_tag(),
                    'outcome_tag_display' => $rule_relation->outcome_tag->display_for_source_rule_relations_outcome_tag(),
                    'engine_rule_display' => $rule_relation->engine_rule->display_for_rule_relations_engine_rule(),
                    'engine_log_display' => $rule_relation->engine_log->display_for_rule_relations_engine_log(),
                    'create_time' => $rule_relation->create_time,
                    'update_time' => $rule_relation->update_time,
                ]
            ];
        }),
    ];
});/*}}}*/

if_post('/rule_relations/add', function ()
{/*{{{*/

    $rule_relation = rule_relation::create(
        input_entity('tag', null, 'source_tag_id'),
        input_entity('tag', null, 'outcome_tag_id'),
        input_entity('engine_rule', null, 'engine_rule_id')
    );

    $rule_relation->engine_log = dao('engine_log')->find(input('engine_log_id'));

    return [
        'id' => $rule_relation->id,
    ];
});/*}}}*/

//todo::detail

if_post('/rule_relations/update/*', function ($rule_relation_id)
{/*{{{*/

    $rule_relation = dao('rule_relation')->find($rule_relation_id);
    otherwise_error_code('RULE_RELATION_NOT_FOUND', $rule_relation->is_not_null());

    $rule_relation->source_tag = input_entity('tag', null, 'source_tag_id');
    $rule_relation->outcome_tag = input_entity('tag', null, 'outcome_tag_id');
    $rule_relation->engine_rule = input_entity('engine_rule', null, 'engine_rule_id');
    $rule_relation->engine_log = dao('engine_log')->find(input('engine_log_id'));

    return true;
});/*}}}*/

if_post('/rule_relations/delete/*', function ($rule_relation_id)
{/*{{{*/
    $rule_relation = dao('rule_relation')->find($rule_relation_id);
    otherwise_error_code('RULE_RELATION_NOT_FOUND', $rule_relation->is_not_null());

    $rule_relation->delete();

    return true;
});/*}}}*/
